<template>
  <a-card :bordered="false">

    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="编号">
              <a-input placeholder="请输入编号" v-model="queryParam.code"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="名称">
              <a-input placeholder="请输入名称" v-model="queryParam.name"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- table区域-begin -->
    <a-row :gutter="8">
      <a-col :span="5">
        <div>
          <!--物料种类表格-->
          <a-table
            ref="table1"
            size="middle"
            rowKey="id"
            class="j-table-force-nowrap1"
            :scroll="{ x: true }"
            :columns="columns"
            :dataSource="dataSource"
            :loading="loading"
            :expandedRowKeys="expandedRowKeys"
            @change="handleTableChange"
            @expand="handleExpand"
            :customRow="rowProperties"
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: getType }"
          >
            <template slot="imgSlot" slot-scope="text">
              <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
              <img
                v-else
                :src="getImgView(text)"
                height="25px"
                alt=""
                style="max-width: 80px; font-size: 12px; font-style: italic"
              />
            </template>
            <template slot="fileSlot" slot-scope="text">
              <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
              <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
                下载
              </a-button>
            </template>
          </a-table>
        </div>
      </a-col>
      <a-col :span="18">
        <div class="table-operator">
          <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
          <a-button v-show="productShow" @click="formulaConnect" type="primary">BOM关联</a-button>
          <a-button type="primary" icon="download" @click="handleExportXls('物料基础信息')">导出</a-button>
          <a-upload
            name="file"
            :showUploadList="false"
            :multiple="false"
            :headers="tokenHeader"
            :action="importExcelUrl"
            @change="handleImportExcel"
          >
            <a-button type="primary" icon="import">导入</a-button>
          </a-upload>
<!--          &lt;!&ndash; 高级查询区域 &ndash;&gt;-->
<!--          <j-super-query-->
<!--            :fieldList="superFieldList"-->
<!--            ref="superQueryModal"-->
<!--            @handleSuperQuery="handleSuperQuery"-->
<!--          ></j-super-query>-->
          <a-dropdown v-if="selectedRowKeys.length > 0">
            <a-menu slot="overlay">
              <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
            </a-menu>
            <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
          </a-dropdown>
        </div>

        <!-- table区域-begin -->
        <div>
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
            <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
            >项
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          </div>
          <!--物料表单-->
          <a-table
            ref="table"
            size="middle"
            :scroll="{ x: true }"
            bordered
            rowKey="id"
            :columns="columns1"
            :dataSource="checkSelectRows"
            :pagination="ipagination"
            :loading="loading1"
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectRow }"
            class="j-table-force-nowrap1"
            @change="handleTableChange">
            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>
            <template slot="imgSlot" slot-scope="text, record">
              <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
              <img
                v-else
                :src="getImgView(text)"
                :preview="record.id"
                height="25px"
                alt=""
                style="max-width: 80px; font-size: 12px; font-style: italic"
              />
            </template>
            <template slot="fileSlot" slot-scope="text">
              <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
              <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
                下载
              </a-button>
            </template>

            <span slot="action" slot-scope="text, record">
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="handleCopy(record)">复制</a>
<!--              <a-divider type="vertical"  v-show="!productShow"/>-->
<!--              <a v-show="!productShow"  @click="handleSupplier(record)">供应商</a>-->
              <a-divider type="vertical" />
              <!--          <a v-if="record.categoryCodeText.includes('成品')" @click="handleCorrelation(record)">关联配方</a>-->
              <!--          <a-divider type="vertical" />-->
              <a-dropdown>
                <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
                <a-menu slot="overlay">
                  <a-menu-item>
                    <a @click="handleDetail(record)">详情</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                      <a>删除</a>
                    </a-popconfirm>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </span>
          </a-table>
        </div>
      </a-col>
    </a-row>
    <erpGoodsAll-modal ref="modalForm" @ok="modalFormOk"></erpGoodsAll-modal>
    <erp-goods-formula-add-model ref="goodsFormula" @ok="modalFormOk"> </erp-goods-formula-add-model>
    <erp-goods-supplier-list ref="goodsSupplier" @ok="modalFormOk"></erp-goods-supplier-list>
  </a-card>
</template>

<script>
import { deleteAction, getAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { filterObj } from '@/utils/util'
import { Message, MessageBox, Notification, Loading } from 'element-ui'

import ErpGoodsCategoryModal from './modules/ErpGoodsCategoryModal'
import ErpGoodsFormulaAddModel from '../base/modules/ErpGoodsFormulaAddModal'
import ErpGoodsAllModal from './modules/ErpGoodsAllModal'

import ErpGoodsModal from './modules/ErpGoodsModal'
import ErpGoodsSupplierList from './ErpGoodsSupplierList.vue'

export default {
  name: 'ErpGoodsList',
  mixins: [JeecgListMixin],
  components: {
    ErpGoodsCategoryModal,
    ErpGoodsFormulaAddModel,
    ErpGoodsAllModal,
    ErpGoodsSupplierList,
  },
  data() {
    return {
      ipagination: {
        current: 1,
        pageSize: 20,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      productShow:false,

      isModalVisible: false,
      checkSelectRows: [],
      selectedRowKeys: [],
      //选中的物料数据集合
      selectedGoods: [],
      expandedRowKeys: [],
      hasChildrenField: 'hasChild',
      pidField: 'parentId',
      dictOptions: {},
      loading: false,
      loading1: false,
      loadParent: false,
      superFieldList: [],
      selectedType: {},
      //点击树查询物料列表条件对象
      category: {
        id: null,
        name: '',
        code: null,
        hasChild: null,
      },
      description: 'erp_goods_category管理页面',

      columns: [
        {
          title: '种类编号',
          align: 'left',
          dataIndex: 'code',
          // defaultSortOrder: 'descend',
          // sorter: (a, b) => a.code.localeCompare(b.code, 'en'),
        },
        {
          title: '种类名称',
          align: 'left',
          dataIndex: 'name',
        },
      ],

      columns1: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '客户物料编码',
          align: 'center',
          dataIndex: 'customCode',
          width: 60
        },
        {
          title: '物料编码',
          align: 'center',
          dataIndex: 'code',
          width: 147
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'name',
          width: 147
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'noneSpec',
          width: 147
        },
/*        {
          title: '物料描述',
          align: 'center',
          dataIndex: 'categoryDescription',
          width: 100
        },*/
        {
          title: '单位',
          align: 'center',
          dataIndex: 'meUnit_dictText',
          width: 60
        },
        {
          title: '辅单位',
          align: 'center',
          dataIndex: 'auUnit_dictText',
          width: 60
        },
        {
          title: '换算率',
          align: 'center',
          dataIndex: 'coRate',
          width: 60
        },
/*        {
          title: '类型',
          align: 'center',
          dataIndex: 'classify_dictText',
          width: 100
        },*/
        {
          title: '仓储仓库',
          align: 'center',
          dataIndex: 'warehouseName',
          width: 100
        },
        {
          title: '材质',
          align: 'center',
          dataIndex: 'materialQuality',
          width: 60
        },
        {
          title: '尺寸',
          align: 'center',
          dataIndex: 'size',
          width: 60
        },
        {
          title: '包材类别',
          align: 'center',
          dataIndex: 'packageCategory',
          width: 100
        },
        {
          title: '包装方式',
          align: 'center',
          dataIndex: 'packageType',
          width: 100
        },
        {
          title: '最小包装量（g）',
          align: 'center',
          dataIndex: 'packSpec',
          width: 60
        },
        {
          title: '最小包装量个数/单位',
          align: 'center',
          dataIndex: 'packSpecNum',
          width: 60
        },
        {
          title: '保质期',
          align: 'center',
          dataIndex: 'qualityDays',
          width: 60
        },
        {
          title: '允许呆滞时长（天）',
          align: 'center',
          dataIndex: 'sluggishHours',
          width: 60
        },
        {
          title: '允许最小库存',
          align: 'center',
          dataIndex: 'minimumInventory',
          width: 60
        },
        {
          title: '允许最大库存',
          align: 'center',
          dataIndex: 'maxInventory',
          width: 60
        },

         {
           title: '物料分类1',
           align: 'center',
           dataIndex: 'customerName_dictText',
           width: 100
         },
        {
          title: '物料分类2',
          align: 'center',
          dataIndex: 'brand_dictText',
          width: 100
        },
        {
          title: '单位/Tray',
          align: 'center',
          dataIndex: 'unitTray',
          width: 60
        },
        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createBy',
          width: 60
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime',
          width: 60
        },
        {
          title: '更新人',
          align: 'center',
          dataIndex: 'updateBy',
          width: 60
        },
        {
          title: '更新时间',
          align: 'center',
          dataIndex: 'updateTime',
          width: 60
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/goods/erpGoodsCategory/queryTopList',
        goodsList: '/base/erpGoods/list',
        queryListByCondition: '/base/erpGoods/queryListByCondition',
        childList: '/goods/erpGoodsCategory/childList',
        getChildListBatch: '/goods/erpGoodsCategory/getChildListBatch',
        delete: '/base/erpGoods/delete',
        deleteBatch: '/base/erpGoods/deleteBatch',
        exportXlsUrl: '/base/erpGoods/exportXls',
        importExcelUrl: '/base/erpGoods/importExcel',
      },
    }
  },
  created() {
    this.getSuperFieldList()
  },
  computed: {
    getType: function () {
      return 'radio'
    },
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    tableProps() {
      let _this = this
      return {
        // 列表项是否可选择
        rowSelection: {
          selectedRowKeys: _this.selectedRowKeys,
          onChange: (selectedRowKeys) => (_this.selectedRowKeys = selectedRowKeys),
        },
      }
    },
  },
  methods: {
    searchQuery(){
      this.loadData(1)
    },
    handleSupplier(record){
      this.$refs.goodsSupplier.edit(record);
    },
    loadData(arg) {
      if (arg == 1) {
        this.ipagination.current = 1
      }
      let params = this.getQueryParams()
      params.hasQuery = 'true'
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          console.log(res, '物料种类列表')
          if (res.success) {
            let result = res.result
            if (Number(result.total) > 0) {
              this.ipagination.total = Number(result.total)
              this.dataSource = this.getDataByResult(res.result.records)
            } else {
              this.ipagination.total = 0
              this.dataSource = []
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
      const hasQueryParams = this.queryParam.code || this.queryParam.name;
      if (!hasQueryParams && this.category) {
        this.getGoods(params)
      }else {
        params=this.getQueryParams()
        params.categoryNo = this.category.code
        getAction(this.url.goodsList, params)
          .then((res) => {
            if (res.success) {
              console.log(res.result)
              let result = res.result
              if (Number(result.total) > 0) {
                this.ipagination.total = Number(result.total)
                this.checkSelectRows = res.result.records
              } else {
                this.checkSelectRows = []
              }
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading1 = false
          })
      }
    },

    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
      this.checkSelectRows = []
      let record = selectionRows[0]
      console.log(record)
      this.category.id = record.id
      this.category.code = record.code
      this.category.name = record.name
      this.category.hasChild = record.hasChild
      this.category.pageNo = this.ipagination.current
      this.category.pageSize = this.ipagination.pageSize
      this.loading1 = true
      getAction(this.url.queryListByCondition, {...this.category,materialCode:this.queryParam.code,materialName:this.queryParam.name})
        .then((res) => {
          if (res.success) {
            console.log(res.result)
            let result = res.result
            if (Number(result.total) > 0) {
              this.ipagination.total = Number(result.total)
              this.checkSelectRows = res.result.records
            } else {
              this.checkSelectRows = []
              this.loading1 = false
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading1 = false
        })
    },

    //点击物料种类数据时
    rowProperties(record, index) {
      return {
        on: {
          click: (event) => {
            this.checkSelectRows = []
            console.log(record)
            this.category.id = record.id
            this.category.code = record.code
            this.category.name = record.name
            this.category.hasChild = record.hasChild
            this.productShow=this.category.code.startsWith("1")
            console.log("this.productShow",this.productShow)
            this.getGoods()
          },
        },
      }
    },
    getQueryParams1() {
      let param = {}
    },
    getGoods() {
      this.category.pageNo = this.ipagination.current
      this.category.pageSize = this.ipagination.pageSize
      this.loading1 = true
      getAction(this.url.queryListByCondition, {...this.category,materialCode:this.queryParam.code,materialName:this.queryParam.name})
        .then((res) => {
          if (res.success) {
            console.log(res.result)
            let result = res.result
            if (Number(result.total) > 0) {
              this.ipagination.total = Number(result.total)
              this.checkSelectRows = res.result.records
            } else {
              this.checkSelectRows = []
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading1 = false
        })
    },
    //选中列表数据执行的方法
    onSelectRow(selectedRowKeys, selectionRows) {
      console.log(1111, selectionRows)
      this.selectedRowKeys = selectedRowKeys

      this.selectedGoods = selectionRows
      console.log(this.selectedGoods)
    },

    // 根据已展开的行查询数据（用于保存后刷新时异步加载子级的数据）
    loadDataByExpandedRows(dataList) {
      if (this.expandedRowKeys.length > 0) {
        return getAction(this.url.getChildListBatch, { parentIds: this.expandedRowKeys.join(',') }).then((res) => {
          if (res.success && res.result.records.length > 0) {
            //已展开的数据批量子节点
            let records = res.result.records
            const listMap = new Map()
            for (let item of records) {
              let pid = item[this.pidField]
              if (this.expandedRowKeys.join(',').includes(pid)) {
                let mapList = listMap.get(pid)
                if (mapList == null) {
                  mapList = []
                }
                mapList.push(item)
                listMap.set(pid, mapList)
              }
            }
            let childrenMap = listMap
            let fn = (list) => {
              if (list) {
                list.forEach((data) => {
                  if (this.expandedRowKeys.includes(data.id)) {
                    data.children = this.getDataByResult(childrenMap.get(data.id))
                    fn(data.children)
                  }
                })
              }
            }
            fn(dataList)
          }
        })
      } else {
        return Promise.resolve()
      }
    },
    getQueryParams(arg) {
      //获取查询条件
      let sqp = {}
      let param = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      if (arg) {
        param = Object.assign(sqp, this.filters)
      } else {
        param = Object.assign(sqp, this.queryParam, this.filters)
      }
      if (JSON.stringify(this.queryParam) === '{}' || arg) {
        param.hasQuery = 'false'
      } else {
        param.hasQuery = 'true'
      }
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    searchReset() {
      //重置
      this.expandedRowKeys = []
      this.queryParam = {}
      this.loadData(1)
    },
    getDataByResult(result) {
      if (result) {
        return result.map((item) => {
          //判断是否标记了带有子节点
          if (item[this.hasChildrenField] == '1') {
            let loadChild = { id: item.id + '_loadChild', name: 'loading...', isLoading: true }
            item.children = [loadChild]
          }
          return item
        })
      }
    },
    handleExpand(expanded, record) {
      // 判断是否是展开状态
      if (expanded) {
        this.expandedRowKeys.push(record.id)
        if (record.children.length > 0 && record.children[0].isLoading === true) {
          let params = this.getQueryParams(1) //查询条件
          params[this.pidField] = record.id
          params.hasQuery = 'false'
          params.superQueryParams = ''
          getAction(this.url.childList, params).then((res) => {
            if (res.success) {
              if (res.result.records) {
                record.children = this.getDataByResult(res.result.records)
                this.dataSource = [...this.dataSource]
              } else {
                record.children = ''
                record.hasChildrenField = '0'
              }
            } else {
              this.$message.warning(res.message)
            }
          })
        }
      } else {
        let keyIndex = this.expandedRowKeys.indexOf(record.id)
        if (keyIndex >= 0) {
          this.expandedRowKeys.splice(keyIndex, 1)
        }
      }
    },
    handleAdd: function () {
      if (!this.category || !this.category.code) {
        this.$message.error('请选择物料种类!')
        return
      }
      if (this.category.hasChild === '1') {
        this.$message.error('请选择最详细的物料种类!')
      }
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.categoryNo = this.category.code
      this.$refs.modalForm.categoryName = this.category.name
      this.$refs.modalForm.disableSubmit = false
    },
    formulaConnect: function () {
      console.log(this.selectedGoods)
      console.log(this.selectedGoods.leng)

      if (this.selectedGoods.length === 1) {
        this.$refs.goodsFormula.add(this.selectedGoods)
        this.$refs.goodsFormula.title = '新增'
        this.$refs.goodsFormula.disableSubmit = false
      } else {
        MessageBox.alert('只能选择一个物料进行配方关联', '系统提示')
        return
      }
    },

    handleCopy(record) {
      this.$refs.modalForm.copy(record)
    },
    handleAddChild(record) {
      this.loadParent = true
      let obj = {}
      obj[this.pidField] = record['id']
      this.$refs.modalForm.add(obj)
    },
    handleDeleteNode(id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      deleteAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          that.loadData(1)
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    batchDel() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return false
      } else {
        let ids = ''
        let that = this
        that.selectedRowKeys.forEach(function (val) {
          ids += val + ','
        })
        that.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: function () {
            that.handleDeleteNode(ids)
            that.onClearSelected()
          },
        })
      }
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'code', text: '编号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'name', text: '名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'parentId', text: '父级ID', dictCode: '' })
      fieldList.push({ type: 'int', value: 'status', text: '状态', dictCode: 'erp_status' })
      fieldList.push({ type: 'string', value: 'remark', text: '备注', dictCode: '' })
      fieldList.push({ type: 'string', value: 'pid', text: '父级节点', dictCode: '' })
      this.superFieldList = fieldList
    },
    showModal() {
      this.isModalVisible = true
    },
    handleOk() {
      // 处理确认事件
      this.isModalVisible = false
    },
    handleCancel() {
      // 处理取消事件
      this.isModalVisible = false
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
